package com.bt.lms.ui.page.course;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bt.lms.constants.CourseBizTypeConstant;
import com.bt.lms.entity.CourseInfo;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.action.course.*;
import com.bt.lms.ui.page.sys.style.BtnStyle;
import com.bt.lms.ui.vo.course.CourseInfoVo;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 课程管理界面
 */
public class CourseInfoList extends VBox {

    /**
     * 宽
     */
    public Integer preWidth = 1280;

    /**
     * 列名固定宽
     */
    private double columnWidth = 200;

    /**
     * 表格
     */
    public TableView tableView;

    /**
     * 首页标签
     */
    public static Label firstLab;

    /**
     * 分页查询事件
     */
    private SearchAction pageEH;

    /**
     * 按钮1
     */
    public static Button oneBtn;

    /**
     * 按钮2
     */
    public static Button twoBtn;

    /**
     * 按钮3
     */
    public static Button threeBtn;

    /**
     * 按钮4
     */
    public static Button fourBtn;

    /**
     * 当前页
     */
    public static Integer currentPageNo = 1;

    /**
     * 每页展示的条数
     */
    public static Integer pageSize = 10;

    /**
     * 分页条件模型
     */
    private Page<CourseInfo> pageCourse;

    /**
     * 课程信息主界面
     */
    public CourseInfoList() {

        //初始化所在位置
        initLocation();
        //初始化分页条件查询
        initPagingConditionQuery();
        //新增课程按钮
        initButton();
        //初始化表格
        initTable();
        //分页页码
        initQuery();
        //2、数据
        loadAndRenderPage();
        Insets insets = new Insets(10);
        this.setPadding(insets);
        this.setSpacing(8);
        this.setPrefWidth(preWidth);

    }


    /**
     * 初始化所在位置
     */
    public void initLocation() {

        HBox hBox = new HBox();
        Insets insets = new Insets(10);
        hBox.setPadding(insets);
        Label label = new Label("当前位置：🏠>教学管理>课程管理");
        Font font = Font.font("仿宋", FontWeight.THIN, FontPosture.REGULAR, 18);
        label.setFont(font);
        hBox.getChildren().add(label);
        this.getChildren().add(hBox);

    }

    /**
     * 初始化分页条件查询
     */
    public void initPagingConditionQuery() {

        //盒子
        HBox hBox = new HBox();
        Insets insets = new Insets(10);
        hBox.setPadding(insets);
        hBox.setSpacing(10);

        //下拉框和文本框
        ComboBox<String> studyCenterCB = new ComboBox<>();
        studyCenterCB.getSelectionModel().select("所属的学习中心");
        studyCenterCB.getItems().add("北京师范大学");
        studyCenterCB.getItems().add("东北师范大学");
        studyCenterCB.getItems().add("西南大学");
        studyCenterCB.setId("studyCenterCB");
        studyCenterCB.setCursor(Cursor.HAND); //鼠标移入添加小手图案

        //适合层次
        ComboBox<String> applyLevelComboBox = new ComboBox<>();
        applyLevelComboBox.getSelectionModel().select("适合层次");
        applyLevelComboBox.getItems().add("高中");
        applyLevelComboBox.getItems().add("大专");
        applyLevelComboBox.getItems().add("本科");
        applyLevelComboBox.getItems().add("其他");
        applyLevelComboBox.setId("applyLevelComboBox");
        applyLevelComboBox.setCursor(Cursor.HAND); //鼠标移入添加小手图案

        //编号搜索框
        TextField codeSearchTF = new TextField();
        codeSearchTF.setId("codeSearchTF");
        codeSearchTF.setPromptText("输入课程编号/课程名称");

        //搜索按钮
        Button searchBtn = new Button("搜索");
        SearchBtnAction searchBtnAction = new SearchBtnAction(this);
        searchBtn.setOnAction(searchBtnAction);
        searchBtn.setCursor(Cursor.HAND); //鼠标移入添加小手图案

        //标签，下拉框，搜索框，按钮放盒子里
        ObservableList<Node> hBoxChildren = hBox.getChildren();
        hBoxChildren.addAll(studyCenterCB, applyLevelComboBox, codeSearchTF, searchBtn);

        //放入主盒子
        ObservableList<Node> children1 = this.getChildren();
        children1.add(hBox);

    }

    /**
     * 新增课程按钮
     */
    public void initButton() {

        HBox hBox = new HBox();
        Insets insets = new Insets(10);
        hBox.setPadding(insets);
        Button addCourseBtn = new Button("新增课程");
        addCourseBtn.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        BtnStyle.addBtn(addCourseBtn);
        CourseInfoAddButtonAction courseInfoAddButtonAction = new CourseInfoAddButtonAction(this);
        addCourseBtn.setOnAction(courseInfoAddButtonAction);
        hBox.getChildren().add(addCourseBtn);
        this.getChildren().add(hBox);
    }

    /**
     * 初始化表格
     */
    public void initTable() {

        //创建表格组件
        tableView = new TableView();

        //创建列头
        TableColumn courseNumberCol = new TableColumn<>("课程编号");
        courseNumberCol.setPrefWidth(130);
        TableColumn courseNameCol = new TableColumn<>("课程名称");
        courseNameCol.setPrefWidth(columnWidth);
        TableColumn courseOpenUnitCol = new TableColumn<>("所属的学习中心");
        courseOpenUnitCol.setPrefWidth(columnWidth);
        TableColumn applyLevelCol = new TableColumn<>("适用层次");
        applyLevelCol.setPrefWidth(columnWidth);
        TableColumn stateCol = new TableColumn<>("状态");
        stateCol.setPrefWidth(150);
        TableColumn operationCol = new TableColumn<>("操作");
        operationCol.setPrefWidth(250);
        //把列头放入表内
        ObservableList columns = tableView.getColumns();
        columns.addAll(courseNumberCol, courseNameCol, courseOpenUnitCol, applyLevelCol, stateCol, operationCol);

        //配置列映射，让每一列知道要展示的属性是哪一个
        courseNumberCol.setCellValueFactory(new PropertyValueFactory<CourseInfoVo, String>("code"));
        courseNameCol.setCellValueFactory(new PropertyValueFactory<CourseInfoVo, HBox>("name"));
        courseOpenUnitCol.setCellValueFactory(new PropertyValueFactory<CourseInfoVo, String>("studyCenter"));
        applyLevelCol.setCellValueFactory(new PropertyValueFactory<CourseInfoVo, String>("applyLevel"));
        stateCol.setCellValueFactory(new PropertyValueFactory<CourseInfoVo, String>("status"));
        operationCol.setCellValueFactory(new PropertyValueFactory<CourseInfoVo, HBox>("operation"));


        //把表放到盒子里
        ObservableList<Node> children = this.getChildren();
        children.add(tableView);

    }

    /**
     * 分页页码
     */
    private void initQuery() {
        //分页查询
        HBox hBox2 = new HBox();
        hBox2.setSpacing(6);
        hBox2.setAlignment(Pos.CENTER_RIGHT);
        firstLab = new Label("<<首页");
        firstLab.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        this.pageEH = new SearchAction();
        this.pageEH.setCourseInfoList(this);
        firstLab.setOnMouseClicked(this.pageEH);
        //颜色
        Color rgb3 = Color.rgb(120, 185, 0);
        firstLab.setTextFill(rgb3);
        Label upLab = new Label("<<上一页");
        upLab.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        upLab.setTextFill(rgb3);
        upLab.setOnMouseClicked(this.pageEH);

        oneBtn = new Button("1");
        oneBtn.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        oneBtn.setOnMouseClicked(this.pageEH);

        twoBtn = new Button("2");
        twoBtn.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        twoBtn.setOnMouseClicked(this.pageEH);

        threeBtn = new Button("3");
        threeBtn.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        threeBtn.setOnMouseClicked(this.pageEH);

        fourBtn = new Button("4");
        fourBtn.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        fourBtn.setOnMouseClicked(this.pageEH);

        Label nextLab = new Label("下一页>>");
        nextLab.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        nextLab.setOnMouseClicked(this.pageEH);

        nextLab.setTextFill(rgb3);
        Label endLab = new Label("尾页>>");
        endLab.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        endLab.setOnMouseClicked(this.pageEH);

        endLab.setTextFill(rgb3);
        Label allLab = new Label("总记录数100条");
        TextField pageTF = new TextField();
        pageTF.setPrefWidth(20);
        Label pageLab = new Label("/10");
        Button goBtn = new Button("GO");
        goBtn.setCursor(Cursor.HAND); //鼠标移入添加小手图案
        hBox2.getChildren().addAll(firstLab, upLab, oneBtn, twoBtn, threeBtn, fourBtn, nextLab, endLab, allLab, pageTF, pageLab, goBtn);

        this.getChildren().add(hBox2);
    }

    /**
     * 搜索事件
     */
    private class SearchAction implements EventHandler {

        /**
         * 所属的分页界面
         */
        private CourseInfoList courseInfoList;

        @Override
        public void handle(Event event) {
            String btnStr = null;
            try {
                Button source = (Button) event.getSource();
                btnStr = source.getText(); //获取按钮内容
            } catch (Exception e) {
//            throw new RuntimeException(e);
                Label source = (Label) event.getSource();
                btnStr = source.getText(); //获取标签内容
            }

            //如果按钮内容是数字时
            if (btnStr.matches("[1-9]\\d*")) {
                //按钮文本转数字
                int btnInt = Integer.parseInt(btnStr);
                if (btnInt > 2) {
                    Button oneBtn = CourseInfoList.oneBtn;
                    oneBtn.setText(String.valueOf(btnInt - 1));
                    Button twoBtn = CourseInfoList.twoBtn;
                    twoBtn.setText(String.valueOf(btnInt));
                    Button threeBtn = CourseInfoList.threeBtn;
                    threeBtn.setText(String.valueOf(btnInt + 1));
                    Button fourBtn = CourseInfoList.fourBtn;
                    fourBtn.setText(String.valueOf(btnInt + 2));
                }
                CourseInfoList.setCurrentPageNo(btnInt);
            } else { //如果按钮内容是数字时
                if (btnStr.equals("<<首页")) {
                    CourseInfoList.currentPageNo = 1;
                    Button oneBtn = CourseInfoList.oneBtn;
                    oneBtn.setText("1");
                    Button twoBtn = CourseInfoList.twoBtn;
                    twoBtn.setText("2");
                    Button threeBtn = CourseInfoList.threeBtn;
                    threeBtn.setText("3");
                    Button fourBtn = CourseInfoList.fourBtn;
                    fourBtn.setText("4");
                }

                if (btnStr.equals("<<上一页")) {
                    CourseInfoList.currentPageNo
                            =  //当前页码如果是1上一页还是1，页码不是1就减去1
                            CourseInfoList.currentPageNo == 1 ? 1 : CourseInfoList.currentPageNo - 1;

                    Button oneBtn = CourseInfoList.oneBtn;
                    oneBtn.setText(String.valueOf(CourseInfoList.currentPageNo));
                    Button twoBtn = CourseInfoList.twoBtn;
                    twoBtn.setText(String.valueOf(CourseInfoList.currentPageNo + 1));
                    Button threeBtn = CourseInfoList.threeBtn;
                    threeBtn.setText(String.valueOf(CourseInfoList.currentPageNo + 2));
                    Button fourBtn = CourseInfoList.fourBtn;
                    fourBtn.setText(String.valueOf(CourseInfoList.currentPageNo + 3));

                }

                if (btnStr.equals("下一页>>")) {
                    CourseInfoList.currentPageNo
                            =
                            CourseInfoList.currentPageNo + 1; //当前页码加1

                    Button oneBtn = CourseInfoList.oneBtn;
                    oneBtn.setText(String.valueOf(CourseInfoList.currentPageNo));
                    Button twoBtn = CourseInfoList.twoBtn;
                    twoBtn.setText(String.valueOf(CourseInfoList.currentPageNo + 1));
                    Button threeBtn = CourseInfoList.threeBtn;
                    threeBtn.setText(String.valueOf(CourseInfoList.currentPageNo + 2));
                    Button fourBtn = CourseInfoList.fourBtn;
                    fourBtn.setText(String.valueOf(CourseInfoList.currentPageNo + 3));
                }
            }
            this.courseInfoList.loadAndRenderPage();
        }

        public CourseInfoList getCourseInfoList() {
            return courseInfoList;
        }

        public void setCourseInfoList(CourseInfoList courseInfoList) {
            this.courseInfoList = courseInfoList;
        }
    }

    /**
     * 加载并渲染 分页
     * 按照当前的页码，加载当前页的数据并渲染到表格中
     */
    private void loadAndRenderPage() {
        Integer pageNo = this.currentPageNo; //当前页数
        this.pageCourse = new Page<>();
        this.pageCourse.setCurrent(pageNo); //获取当前页

        //组包
        //消息
        ReqMsg reqMsg = new ReqMsg();
        //业务类型
        reqMsg.setBizType(CourseBizTypeConstant.COURSE_PAGE_CONDITION_QUERY);
        String courseStr = JSON.toJSONString(this.pageCourse);
        //数据带走
        reqMsg.setData(courseStr);
        byte[] bytes = reqMsg.toBytes();

        //组网
        String serverIp = "127.0.0.1";
        int serverPort = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverIp, serverPort);
        } catch (IOException e) {
//            throw new RuntimeException(e);
        }

        //发送请求消息
        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush(); //冲刷
        } catch (IOException e) {
//            throw new RuntimeException(e);
        }

        //接收回应信息
        try {
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1500];
            in.read(buf);
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();
            Page page = JSONObject.parseObject(data, Page.class);
            List records = page.getRecords(); //查询数据列表

            List<CourseInfo> courseInfos = new ArrayList<>();//给个集合
            //循环取数据
            for (int i = 0; i < records.size(); i++) {
                Object courseObj = records.get(i);
                String courseStr1 = courseObj.toString();
                CourseInfo courseInfo = JSONObject.parseObject(courseStr1, CourseInfo.class);
                courseInfos.add(courseInfo); //放入集合
            }

            //处理数据里的集合
            ArrayList<CourseInfoVo> courseInfoVos = new ArrayList<>();

            for (int i = 0; i < courseInfos.size(); i++) {

                CourseInfo courseInfo = courseInfos.get(i);
                //课程编号
                String code = courseInfo.getCode();
                //课程名称
                HBox nameHBox = new HBox();
                Label nameLab = new Label("语文");
                nameLab.setCursor(Cursor.CLOSED_HAND);
                DetailCourseBtnAction detailCourseBtnAction = new DetailCourseBtnAction(this);
                nameLab.setOnMouseClicked(detailCourseBtnAction);

                nameHBox.getChildren().add(nameLab);
                Color rgb = Color.rgb(49, 193, 231);
                nameLab.setTextFill(rgb);
                //所属的学习中心
                Integer studyCenter = courseInfo.getStudyCenter();
                String studyCenterStr = null;
                switch (studyCenter) {
                    case 1:
                        studyCenterStr = "北京师范大学";
                        break;
                    case 2:
                        studyCenterStr = "东北师范大学";
                        break;
                    case 3:
                        studyCenterStr = "西南大学";
                        break;
                }
                //适用层次
                Integer applyLevel = courseInfo.getApplyLevel();
                String applyLevelStr = null;
                switch (applyLevel) {
                    case 1:
                        applyLevelStr = "高中";
                        break;
                    case 2:
                        applyLevelStr = "大专";
                        break;
                    case 3:
                        applyLevelStr = "本科";
                        break;
                    case 4:
                        applyLevelStr = "其他";
                        break;
                }
                //状态
                Integer status = courseInfo.getStatus();
                String statusStr = null;
                switch (status) {
                    case 1:
                        statusStr = "未启用";
                        break;
                    case 2:
                        statusStr = "启用";
                        break;
                    case 3:
                        statusStr = "停用";
                        break;
                }

                HBox operationHBox = new HBox();
                operationHBox.setSpacing(10);
                if (status.equals(1)) {
                    Button startBtn = new Button("启用");
                    startBtn.setCursor(Cursor.HAND);
                    StartCourseBtnAction startCourseBtnAction = new StartCourseBtnAction(this);
                    startBtn.setOnAction(startCourseBtnAction);
                    Button editBtn = new Button("编辑");
                    editBtn.setCursor(Cursor.HAND);
                    CourseInfoEditBtnAction courseInfoEditBtnAction = new CourseInfoEditBtnAction(this);
                    editBtn.setOnAction(courseInfoEditBtnAction);
                    Button deleteBtn = new Button("删除");
                    deleteBtn.setCursor(Cursor.HAND);
                    CourseINfoDeleteBtnAction courseINfoDeleteBtnAction = new CourseINfoDeleteBtnAction(this);
                    deleteBtn.setOnAction(courseINfoDeleteBtnAction);
                    operationHBox.getChildren().addAll(startBtn, editBtn, deleteBtn);
                } else if (status.equals(2)) {
                    Button stopBtn = new Button("停用");
                    stopBtn.setCursor(Cursor.HAND);
                    StopCourseBtnAction stopCourseBtnAction = new StopCourseBtnAction(this);
                    stopBtn.setOnAction(stopCourseBtnAction);
                    Button editBtn = new Button("编辑");
                    editBtn.setCursor(Cursor.HAND);
                    CourseInfoEditBtnAction courseInfoEditBtnAction = new CourseInfoEditBtnAction(this);
                    editBtn.setOnAction(courseInfoEditBtnAction);
                    Button deleteBtn = new Button("删除");
                    deleteBtn.setCursor(Cursor.HAND);
                    CourseINfoDeleteBtnAction courseINfoDeleteBtnAction = new CourseINfoDeleteBtnAction(this);
                    deleteBtn.setOnAction(courseINfoDeleteBtnAction);
                    operationHBox.getChildren().addAll(stopBtn, editBtn, deleteBtn);
                } else if (status.equals(3)) {
                    Button startBtn = new Button("启用");
                    startBtn.setCursor(Cursor.HAND);
                    StartCourseBtnAction startCourseBtnAction = new StartCourseBtnAction(this);
                    startBtn.setOnAction(startCourseBtnAction);
                    Button editBtn = new Button("编辑");
                    editBtn.setCursor(Cursor.HAND);
                    CourseInfoEditBtnAction courseInfoEditBtnAction = new CourseInfoEditBtnAction(this);
                    editBtn.setOnAction(courseInfoEditBtnAction);
                    Button deleteBtn = new Button("删除");
                    deleteBtn.setCursor(Cursor.HAND);
                    CourseINfoDeleteBtnAction courseINfoDeleteBtnAction = new CourseINfoDeleteBtnAction(this);
                    deleteBtn.setOnAction(courseINfoDeleteBtnAction);
                    operationHBox.getChildren().addAll(startBtn, editBtn, deleteBtn);
                }


                CourseInfoVo courseInfoVo = new CourseInfoVo(code, nameHBox, studyCenterStr, applyLevelStr, statusStr, operationHBox);
                courseInfoVos.add(courseInfoVo);
            }


            ObservableList<CourseInfoVo> courseInfoVos1 = FXCollections.observableArrayList(courseInfoVos);
            tableView.setItems(courseInfoVos1); //数据放入表格中
        } catch (IOException e) {
//            throw new RuntimeException(e);
        }

    }


    public Integer getPreWidth() {
        return preWidth;
    }

    public void setPreWidth(Integer preWidth) {
        this.preWidth = preWidth;
    }

    public double getColumnWidth() {
        return columnWidth;
    }

    public void setColumnWidth(double columnWidth) {
        this.columnWidth = columnWidth;
    }

    public TableView getTableView() {
        return tableView;
    }

    public void setTableView(TableView tableView) {
        this.tableView = tableView;
    }

    public static Label getFirstLab() {
        return firstLab;
    }

    public static void setFirstLab(Label firstLab) {
        CourseInfoList.firstLab = firstLab;
    }

    public static Button getOneBtn() {
        return oneBtn;
    }

    public static void setOneBtn(Button oneBtn) {
        CourseInfoList.oneBtn = oneBtn;
    }

    public static Button getTwoBtn() {
        return twoBtn;
    }

    public static void setTwoBtn(Button twoBtn) {
        CourseInfoList.twoBtn = twoBtn;
    }

    public static Button getThreeBtn() {
        return threeBtn;
    }

    public static void setThreeBtn(Button threeBtn) {
        CourseInfoList.threeBtn = threeBtn;
    }

    public static Button getFourBtn() {
        return fourBtn;
    }

    public static void setFourBtn(Button fourBtn) {
        CourseInfoList.fourBtn = fourBtn;
    }

    public static Integer getCurrentPageNo() {
        return currentPageNo;
    }

    public static void setCurrentPageNo(Integer currentPageNo) {
        CourseInfoList.currentPageNo = currentPageNo;
    }

    public static Integer getPageSize() {
        return pageSize;
    }

    public static void setPageSize(Integer pageSize) {
        CourseInfoList.pageSize = pageSize;
    }

    public SearchAction getPageEH() {
        return pageEH;
    }

    public void setPageEH(SearchAction pageEH) {
        this.pageEH = pageEH;
    }

    public Page<CourseInfo> getPageCourse() {
        return pageCourse;
    }

    public void setPageCourse(Page<CourseInfo> pageCourse) {
        this.pageCourse = pageCourse;
    }
}
